package cn.zz.veggie.web.controller.mgmt;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.zz.comm.types.result.R;
import cn.zz.veggie.web.types.vo.FileUploadVo;
import cn.zz.veggie.core.enums.biz.BizFileType;
import cn.zz.veggie.tool.config.FileUploadConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;

/**
 * 管理端/文件上传
 *
 * @author zhongq
 * @since 2024/4/27
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/mgmt/upload")
public class MgmtFileUploadController {

	private final FileUploadConfig fileUploadConfig;

	/**
	 * 上传商品图片
	 */
	@PostMapping("/product")
	public R<FileUploadVo> uploadProductImage(@RequestParam MultipartFile file) {
		final String targetPath = saveFile(file, BizFileType.product);
		return R.ok(new FileUploadVo(targetPath));
	}

	/**
	 * 上传用户头像
	 */
	@PostMapping("/avatar")
	public R<String> uploadAvatarImage(@RequestParam MultipartFile file) {
		final String targetPath = saveFile(file, BizFileType.avatar);
		return R.ok(targetPath);
	}

	private String saveFile(MultipartFile file, BizFileType bizFileType) {
		String baseDir = fileUploadConfig.getBasePath();
		final String dateDir = DatePattern.NORM_DATE_FORMATTER.format(LocalDate.now());
		final String fileName = UUID.fastUUID().toString(true) + "." + FileUtil.getSuffix(file.getOriginalFilename());
		String targetPath = String.join(File.separator, bizFileType.name(), dateDir, fileName);
		File targetFile = new File(baseDir, targetPath);
		FileUtil.touch(targetFile);
		try {
			file.transferTo(targetFile);
			log.info("upload success biz:  {} , {} , to {} ", bizFileType, file.getOriginalFilename(), targetFile);
			return String.join("/", dateDir, fileName);
		} catch (IOException e) {
			log.error("upload fail biz:  {} ,  {} , to {} ", bizFileType, file.getOriginalFilename(), targetFile, e);
			return null;
		}
	}

}